import {Service, action} from "adajs";

class InputService extends Service {
	defaultData() {
		return {
			name: "",
			label: "",
			placeholder: "",
			inputType: "text",
			description: "",
			value: "",
			error: false,
			errorMsg: "",
			required: false,
			check: null,
			count: 60,
			url: "/api/app/sms/sendSmsCode",
			sended: false,
			btnState: {
				label: "获取验证码",
				disable: false
			}
		};
	}

	onupdate(current, data) {
		Object.assign(current, data);
	}

	@action("setValue")
	setValue(current, value) {
		current.value = value;
	}

	@action("showError")
	showError(current, info) {
		current.error = true;
		current.errorMsg = info || "";
	}

	@action("hideError")
	hideError(current) {
		current.error = false;
	}

	@action("check")
	check(current, value) {
		if (current.required) {
			if (!value) {
				current.error = true;
				current.errorMsg = '字段不能为空';
			} else {
				if(!current.sended){
					current.error = true;
					current.errorMsg = '先获取验证码';
				}else {
					current.error = false;
				}
			}
		}
		if (!current.error && current.check) {
			return Promise.resolve().then(current.check(current, value));
		}
	}

	@action("setBtnState")
	setBtnState(current, state) {
		current.stateStr = state;
	}

	@action("send")
	send(current) {
		return this.context.request.get(current.url).then(() => {
			current.btnState.disable = true;
			current.sended = true;
		});
	}

	@action("setBtnTime")
	setBtnTime(current, time) {
		current.btnState.label = `${time}s`;
		if (time === 0) {
			current.btnState.label = '重新获取';
			current.btnState.disable = false;
		} else {
			current.btnState.disable = true;
		}
	}
}

export default InputService;